package cn.antcore.common.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.session.web.http.HttpSessionIdResolver;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;

/**
 * 自定义Session取值参数
 * <br>
 * Created by Hong 2024/5/30
**/
public class SessionIdResolver implements HttpSessionIdResolver {
    private static final String HEADER_X_AUTH_TOKEN = "X-Auth-Token";
    private final String headerName;

    public static SessionIdResolver xAuthToken() {
        return new SessionIdResolver(HEADER_X_AUTH_TOKEN);
    }

    public SessionIdResolver(String headerName) {
        if (headerName == null) {
            throw new IllegalArgumentException("headerName cannot be null");
        } else {
            this.headerName = headerName;
        }
    }

    public List<String> resolveSessionIds(HttpServletRequest request) {
        String headerValue = request.getHeader(this.headerName);
        if (!StringUtils.hasText(headerValue)) {
            // Header中不存在就从入参中取
            headerValue = request.getParameter(this.headerName);
        }
        return headerValue != null ? Collections.singletonList(headerValue) : Collections.emptyList();
    }

    public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
        response.setHeader(this.headerName, sessionId);
    }

    public void expireSession(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader(this.headerName, "");
    }
}
